package com.mengtian_tech.tju.dataquery.api.service;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.mengtian_tech.tju.dataquery.api.model.QueryType;

@Service
public class QueryLogService {

	
	@Autowired
	@Qualifier("jdbcTemplateDataAi")
	JdbcTemplate jdbcTemplateDataAi;
	
	@Autowired
	EmployeeService employeeService;
	
	public void addLog(String userId,QueryType type,String key,String remark) {
		addLog(userId,type.getCode(),key,remark);
	}
	
	public void addLog(String userId,String type,String key,String remark) {
		
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest req = attrs.getRequest(); // 获取当前会话
		String ip = req.getHeader("X-Forwarded-For");
	    String userAgent = req.getHeader("User-Agent");
	     
		String userName = this.employeeService.findNameById(userId);
		this.jdbcTemplateDataAi.update("insert into query_log (create_date,user_id,user_name,opt_type,query_key,remark,ip,client_agent) "
				+ " values(now(),?,?,?,?,?,?,?)",userId,userName,type,key,remark,ip,userAgent);
	}
}
